package com.itheima.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.itheima.cammon.PageInof;
import com.itheima.mapper.DishMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.dto.flavorsDto;
import com.itheima.service.DishService;
import com.itheima.vo.DishFlavors;
import com.itheima.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 王同学
 */
@Service
@Slf4j
public class DishServiceimpl implements DishService {
    @Autowired
    DishMapper dishMapper;
    @Autowired
    CategoryServiceimpl categoryServiceimpl;

    //新增菜品
    @Override
    public boolean add(Dish dish) {
        DishVO dishVO = new DishVO();
        //搞个雪花id
        String id = IdUtil.getSnowflakeNextIdStr();
        dish.setId(id);

        /*复制一份给前端看*/
        BeanUtils.copyProperties(dish, dishVO);

        //获取当前口味集合
        List<flavorsDto> flavors = dishVO.getFlavors();

        ArrayList<DishFlavors> newlis = new ArrayList<>();
        //判断集合是否为空 //这种写法性能低，sql性能下降
        if (!CollectionUtil.isEmpty(flavors)) {
            //遍历集合并插入到数据库中
            for (flavorsDto demo : flavors) {
                //如果为空就跳过
                if (demo == null) {
                    continue;
                }
                DishFlavors dishFlavors = new DishFlavors();

                //传值进去
                dishFlavors.setValue(demo.getValue());
                dishFlavors.setName(demo.getName());
                //给他创建一个id
                String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
                dishFlavors.setId(snowflakeNextIdStr);
                dishFlavors.setDishId(id);
                //将口味添加到数据库里面
//                int res = dishMapper.addFlavors(dishFlavors);
//                if (res!=1){
//                    //这边触发运行时异常，进行事务回滚
//                    throw new  RuntimeException("口味添加失败");
//                }
                newlis.add(dishFlavors);
            }
            //返回结果
        }
        int rs = dishMapper.batchAddFlavors(newlis);
        if (rs != newlis.size()) {
            throw new RuntimeException("口味添加失败~！");
        }
        String categoryId = dish.getCategoryId();
        Category category = categoryServiceimpl.finById(categoryId);
        dish.setCategoryName(category.getName());
        int res = dishMapper.add(dish);
        return res > 0;
    }

    //分页查询
    @Override
    public PageInof<Dish> page(String name, Integer page, Integer pageSize, Integer type) {
        //分页查询

        //分页查询的响应结果
        //先new一下调用
        PageInof pageInof = new PageInof<Dish>();
        //页码长度公式
        Integer page1 = (page - 1) * pageSize;
        List<Dish> emp = dishMapper.page(name, page1, pageSize, type);
        pageInof.setRecords(emp);
        pageInof.setSize(pageSize);
        pageInof.setCurrent(page1);
        return pageInof;
    }

    @Override
    public boolean delete(String id) {
        //根据菜品ids来去删除

        //把接收来的字符串拆分成数组,通过这个逗号区分
        String[] splis=id.split(",");
        if (splis.length==0){
            throw new RuntimeException("入参不能为空");
        }
        List<String> list= Arrays.asList(splis);
        //这边去删除
        boolean delete = dishMapper.delete(list);
        if (!delete){
            throw new RuntimeException("删除菜品失败~！！");
        }
        //删除菜品的口味
      boolean res1=  dishMapper.delByFlavoreDishIds(list);
        if (!res1){
            throw new RuntimeException("删除口味失败~！！");
        }

        return true;
    }

    @Override
    public boolean update(Dish dish) {
        //进来的时候先判断是否为空
        if (dish==null){
            log.error("菜品更新数据不能为空");
            return false;
        }
       //1.提取菜品信息，覆盖到菜品里武
        //先调用这个对象
        DishVO dishVO=new DishVO();

        dish.setUpdateTime(LocalDateTime.now());
        //然后把这个对象copy进去
        BeanUtils.copyProperties(dish,dishVO);
        int res = dishMapper.updateById(dishVO);
        if (res!=1){
            log.error("菜品更新失败~！");
            //如果这边受影响行数不等于1的话，说明更新失败
            return false;
        }
        // 3．重建菜品和口味的关系*/
        //先查询口味的个数 计算总个数
     int number = dishMapper.countByFlavoreDishId(dish.getId());
     if (number>0){
         //通过id删除原本菜品的口味
         int FlavoreId=dishMapper.delByFlavoreDishId(dish.getId());
         //
         if (FlavoreId!=number){
             throw new RuntimeException("口味删除失败~!!!!");
         }
     }
        //获取当前口味集合
        List<flavorsDto> flavors = dishVO.getFlavors();

        ArrayList<DishFlavors> newlis = new ArrayList<>();
        //判断集合是否为空 //这种写法性能低，sql性能下降
        if (!CollectionUtil.isEmpty(flavors)) {
            //遍历集合并插入到数据库中
            for (flavorsDto demo : flavors) {
                //如果为空就跳过
                if (demo == null) {
                    continue;
                }
                DishFlavors dishFlavors = new DishFlavors();

                //传值进去
                dishFlavors.setValue(demo.getValue());
                dishFlavors.setName(demo.getName());
                //给他创建一个id
                String snowflakeNextIdStr = IdUtil.getSnowflakeNextIdStr();
                dishFlavors.setId(snowflakeNextIdStr);
                dishFlavors.setDishId(dish.getId());

                newlis.add(dishFlavors);
            }
        }
        int rs = dishMapper.batchAddFlavors(newlis);
        if (rs != newlis.size()) {
            throw new RuntimeException("口味添加失败~！");
        }

        return true;
    }

    @Override
    public boolean updatestatus(String ids,int status) {

        //设置启售和禁售
        int res = dishMapper.status(ids,status);
        if (res<=0){
            throw new RuntimeException("启用/禁用失败");
        }
        return true;
    }
    //通过菜品id查找
    @Override
    public Dish findById(String id) {
        Dish res = dishMapper.findById(id);
        return res;
    }
    //菜品下拉列表
    @Override
    public List<Dish> findAll(String categoryId) {
        List<Dish> all = dishMapper.findAll(categoryId);
        //根据菜品id去找到口味id

        return all;
    }



}
